//
//  ResultPlugin.swift
//  CooperSwift
//
//  Created by Mac on 2019/12/25.
//  Copyright © 2019 CooperSwift. All rights reserved.
//

import Foundation
import Moya
import SwiftyJSON
import CryptoSwift
import RxSwift

struct ResultPlugin: PluginType {
    
    /// Called to modify a request before sending.
    func prepare(_ request: URLRequest, target: TargetType) -> URLRequest { 
        return request
    }
    
    /// Called immediately before a request is sent over the network (or stubbed).
    func willSend(_ request: RequestType, target: TargetType) {
        
    }
    
    /// Called after a response has been received, but before the MoyaProvider has invoked its completion handler.
    func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType) {
        
    }
    
    /// Called to modify a result before completion.
    func process(_ result: Result<Moya.Response, MoyaError>, target: TargetType) -> Result<Moya.Response, MoyaError> {
        if case let .success(response) = result {
            // 判断数据解析转换
            guard let data = try? response.mapString(), let resultModel = ResultModel.deserialize(from: data) else {
                return result
            }
            if resultModel.code == 0 {
                guard let data = resultModel.data else {
                    return result
                }
                guard let data = try? JSONSerialization.data(withJSONObject: data, options: []) else { return result }
                let response = Moya.Response.init(statusCode: 200, data: Data(data))
                return Result.success(response)
            }
        }
        return result
    }
    
}
